package com.sun.enhancespringdatajpa.controller;


import com.alibaba.fastjson.JSON;
import com.sun.enhancespringdatajpa.entity.User;
import com.sun.enhancespringdatajpa.repostory.UserRepository;
import com.sun.enhancespringdatajpa.util.SpecificationFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserRepository repository;

    @GetMapping("/test")
    public Page<User> test(){
        // 传值
        User user = new User();
        user.setNickName("user");
        // 构造条件
        Specification specification = SpecificationFactory.lt("createTime", new Date().getTime());
        specification = specification.and(SpecificationFactory.likeEnd("nickName", user.getNickName()));
        specification = specification.and(SpecificationFactory.isNotNull("phone"));
        // 打印结果
       return repository.findAll(specification,PageRequest.of(0,20,Sort.Direction.DESC,"id"));
    }


    @GetMapping("/sp")
    public List<User> findUserBySpecification() {
        User user = new User();
        user.setNickName("小鱼");

        Specification<User> specification = (root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            //  模糊查询
            if (user.getNickName() != null && user.getNickName().length() > 0) {
                predicates.add(builder.like(root.get("nickName"), user.getNickName() + "%"));
            }
            //  日期比较
            if (user.getCreateTime() != null) {
                predicates.add(builder.greaterThanOrEqualTo(root.get("createTime").as(String.class), "2020-11-21 14:54:42"));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };

       return  repository.findAll(specification);
    }

    @GetMapping("/page2")
    public Page<User> findUserDataPage2() {
        User user = new User();
        user.setNickName("user");
        ExampleMatcher nickName = ExampleMatcher.matching().withMatcher("nickName", ExampleMatcher.GenericPropertyMatchers.startsWith());
        Example<User> example = Example.of(user, nickName);
        return repository.findAll(example, PageRequest.of(0, 10, Sort.Direction.DESC, "id"));
    }


    @GetMapping("/page")
    public Page<User> findUserDataPage() {
        User user = new User();
        ExampleMatcher nickName = ExampleMatcher.matching().withMatcher("nickName",
                ExampleMatcher.GenericPropertyMatchers.exact())
                .withIgnoreCase();
        Example<User> example = Example.of(user, nickName);
        return repository.findAll(example, PageRequest.of(0, 10));
    }

    @GetMapping("/findAll")
    public List<User> findAll() {
        return repository.findAll();
    }

    @GetMapping("/findByName/{name}")
    public List<User> findByName(@PathVariable("name") String name) {
        return repository.findUserInfoByLikeName(name);
    }

    @GetMapping("/add")
    public void insertData() {
        List<User> userList = JSON.parseArray("[\n" +
                "{\n" +
                "\"id\": 4,\n" +
                "\"phone\": \"13456789011\",\n" +
                "\"password\": \"\",\n" +
                "\"nickName\": \"user_slxaxy2au9f3tanffaxr\",\n" +
                "\"icon\": \"\",\n" +
                "\"createTime\": \"2022-01-07T04:07:53.000+00:00\",\n" +
                "\"updateTime\": \"2022-01-07T04:07:53.000+00:00\"\n" +
                "},\n" +
                "{\n" +
                "\"id\": 6,\n" +
                "\"phone\": \"13456762069\",\n" +
                "\"password\": \"\",\n" +
                "\"nickName\": \"user_xn5wr3hpsv\",\n" +
                "\"icon\": \"\",\n" +
                "\"createTime\": \"2022-02-07T09:54:10.000+00:00\",\n" +
                "\"updateTime\": \"2022-02-07T09:54:10.000+00:00\"\n" +
                "},\n" +
                "{\n" +
                "\"id\": 10,\n" +
                "\"phone\": \"13688668889\",\n" +
                "\"password\": \"\",\n" +
                "\"nickName\": \"user_88arndojw9\",\n" +
                "\"icon\": \"\",\n" +
                "\"createTime\": \"2022-02-28T02:50:47.000+00:00\",\n" +
                "\"updateTime\": \"2022-02-28T02:50:47.000+00:00\"\n" +
                "}]", User.class);
        List<User> list = repository.saveAll(userList);
        System.out.println(list);
    }

    @GetMapping("/page/{nickName}")
    public Page<User> findByCondition(@PathVariable("nickName") String nickName) {
        //Sort.Direction是个枚举有ASC(升序)和DESC(降序)
        Sort.Direction sort = Sort.Direction.DESC;
        //PageRequest继承于AbstractPageRequest并且实现了Pageable
        //获取PageRequest对象 index:页码 从0开始  size每页容量 sort排序方式 "id"->properties 以谁为准排序
        Pageable pageable = PageRequest.of(0, 2, sort, "id");
        //要匹配的实例对象
        User user = new User();
        user.setNickName(nickName);
        //定义匹配规则 匹配"vendorId"这个属性 exact 精准匹配
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().
                withMatcher("nickName", ExampleMatcher.GenericPropertyMatchers.exact());
        ;
        Example<User> userExample = Example.of(user, exampleMatcher);
        Page<User> page = repository.findAll(userExample, pageable);
        //获取总页数
        page.getTotalPages();
        //获取总元素个数
        page.getTotalElements();
        //获取该分页的列表
        page.getContent();
        return page;
    }


    @GetMapping("/update")
    public void updateUser() {
        User user = new User();
        user.setId(3);
        user.setNickName("wangwu22");
        user.setPhone("88888888");
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        //repository.save(user); //第一种方式
        repository.updateUserInfoById(user);

    }
}
